package com.example.xiongan_app_yy;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.WindowManager;

import com.example.xiongan_app_yy.activity.MapActivity;
import com.example.xiongan_app_yy.plugin.FlutterPluginCounter;
import com.example.xiongan_app_yy.utils.AESUtil;
import com.senter.support.openapi.StBarcodeScanner;
import com.xuexiang.xqrcode.XQRCode;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "com.example.xiongan_app_yy";
    AtomicBoolean isScanning = new AtomicBoolean(false);
    private MethodChannel.Result results;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        GeneratedPluginRegistrant.registerWith(this);
        FlutterPluginCounter.registerWith(this.registrarFor(FlutterPluginCounter.CHANNEL0));
        new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
                new MethodChannel.MethodCallHandler() {
                    @Override
                    public void onMethodCall(MethodCall call, MethodChannel.Result result) {
                        if (call.method.equals("getPlatformVersion")) {
                            result.success("Android " + android.os.Build.VERSION.RELEASE);
                        } else if (call.method.equals("encrypt")) {
                            String data = call.argument("data");
                            String key = call.argument("key");
                            String iv = call.argument("iv");
                            android.util.Log.e("wu", "onMethodCall: " + call.arguments.toString());
                            String cipherText = null;
                            try {
                                cipherText = AESUtil.encryptAES(data, key, iv);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            result.success(cipherText);
                        } else if (call.method.equals("decrypt")) {
                            String data = call.argument("data");
                            String key = call.argument("key");
                            String iv = call.argument("iv");
                            String text = null;
                            try {
                                text = AESUtil.decryptAES(data, key, iv);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            result.success(text);
                        } else if (call.method.equals("map")) {
                            startActivity(new Intent(MainActivity.this, MapActivity.class));
                            result.success("ok");
                        } else if (call.method.equals("scan")) {
                            scan(result);
                        } else if (call.method.equals("scanCode")) {
                            results = result;
                           //  XQRCode.startScan(MainActivity.this, 200);
                            startActivityForResult(new Intent(MainActivity.this, ScanActivity.class), 200);
                        } else {
                            result.notImplemented();
                        }
                    }
                });
    }

    private void scan(MethodChannel.Result result) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!isScanning.compareAndSet(false, true)) {//at the same time only one thread can be allowed to scan
                    return;
                }
                try {
                    StBarcodeScanner scanner = StBarcodeScanner.getInstance();
                    if (scanner == null) {
                        return;
                    }
                    StBarcodeScanner.BarcodeInfo rslt = scanner.scanBarcodeInfo();
                    AtomicReference<String> show = new AtomicReference<String>("");
                    if (rslt != null) {
                        show.set(new String(rslt.getBarcodeValueAsBytes(), "utf-8"));
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            result.success(show.get());
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    isScanning.set(false);
                }
            }
        }).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == RESULT_OK) {
            if (data != null) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    if (bundle.getInt(XQRCode.RESULT_TYPE) == XQRCode.RESULT_SUCCESS) {
                        String result = bundle.getString(XQRCode.RESULT_DATA);
                        results.success(result);
                    } else if (bundle.getInt(XQRCode.RESULT_TYPE) == XQRCode.RESULT_FAILED) {
                        results.success("");
                    }
                }
            }
        }
    }
}
